package cn.silver.module.message.service.impl;

import cn.silver.framework.mybatis.service.impl.BusServiceImpl;
import cn.silver.module.message.bean.MessageBean;
import cn.silver.module.message.domain.MsgMessage;
import cn.silver.module.message.mapper.MsgMessageMapper;
import cn.silver.module.message.param.MessageParam;
import cn.silver.module.message.service.IMsgMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 短消息Service业务层处理
 *
 * @author hb
 * @date 2022-12-12
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MsgMessageServiceImpl extends BusServiceImpl<MsgMessageMapper, MsgMessage, MessageParam, MessageBean>
        implements IMsgMessageService {

//    private final UserService userService;
//    private final ISysMsgAttachService attachService;
//    private final ISysMsgRecordService recordService;
//    private final ISysMsgReceiverService receiverService;
//    private final ISysMsgTemplateContentService contentService;
//
//    @Override
//    @SneakyThrows
//    public ResultPage<SysMsg> selectPage(PageDomain domain, SysMsg entity) {
//        String beTime = entity.getBeginTime();
//        String enTime = entity.getEndTime();
//        entity.setBeginTime(null);
//        entity.setEndTime(null);
//        QueryWrapper<SysMsg> queryWrapper = this.buildQueryWrapper(entity);
//        if (StringUtils.isNotEmpty(beTime) && StringUtils.isNotEmpty(enTime)) {
//            queryWrapper.between("create_time", DateUtils.parseDate(beTime, "yyyy-MM-dd"), DateUtils.parseDate(enTime, "yyyy-MM-dd"));
//        }
//        domain.setIsAsc("desc");
//        Page<SysMsg> page = baseMapper.selectPage(this.build(domain), queryWrapper);
//        if (page.getTotal() > 0) {
//            List<SysMsgReceiver> receivers = this.receiverService.selectList(new QueryWrapper<SysMsgReceiver>()
//                    .in("msg_id", page.getRecords().stream().map(SysMsg::getId).collect(Collectors.toList())));
//            Map<String, List<SysMsgReceiver>> receiverMap = receivers.stream().collect(Collectors.groupingBy(SysMsgReceiver::getMsgId));
//            page.getRecords().stream().forEach(item -> {
//                item.setChannels(Arrays.asList(item.getChannel().split(",")));
//                item.setReceivers(receiverMap.get(item.getId()));
//            });
//        }
//        return new ResultPage<>(page.getRecords(), page.getTotal());
//    }
//
//    @Override
//    public SysMsg selectById(String id) {
//        SysMsg entity = this.baseMapper.selectById(id);
//        if (StringUtils.isNotBlank(entity.getChannel())) {
//            entity.setChannels(Arrays.asList(entity.getChannel().split(",")));
//        }
//        return entity;
//    }
//
//    @Override
//    public MsgModel selectModel(String id, String channel) {
//        SysMsg msg = this.baseMapper.selectById(id);
//        if (msg != null) {
//            MsgModel model = msg.convertModel();
//            List<SysMsgReceiver> receivers = this.receiverService.selectList(new QueryWrapper<SysMsgReceiver>().eq("msg_id", id)
//                    .eq("channel", channel).eq("status", MsgResult.NO_SEND.getCode()));
//            List<UserModel> models = this.userService.selectByUserIds(receivers.stream().map(SysMsgReceiver::getUserId).collect(Collectors.toList()));
//            model.setReceivers(models);
//            return model;
//        } else {
//            return null;
//        }
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
//    public void sendMessage(MsgModel model) {
//        this.insert(new SysMsg(model));
//    }
//
//    @Override
//    public void updateMsgResult(MsgResultModel model) {
//        SysMsgReceiver receiver = this.receiverService.selectOne(new QueryWrapper<SysMsgReceiver>().eq("msg_id", model.getMsgId())
//                .eq("user_id", model.getUserId()).eq("channel", model.getChannel()));
//        if (receiver != null) {
//            this.receiverService.updateReceiverStatus(receiver, model.getResult());
//            this.recordService.insert(new SysMsgRecord(receiver, model));
//        }
//    }
//
//    @Override
//    public void updateMsgResult(String msgId, String channel, List<MsgResultModel> result) {
//        if (CollectionUtils.isNotEmpty(result)) {
//            List<SysMsgReceiver> receivers = this.receiverService.selectList(new QueryWrapper<SysMsgReceiver>().eq("msg_id", msgId).eq("channel", channel));
//            Map<String, SysMsgReceiver> receiverMap = receivers.stream().collect(Collectors.toMap(SysMsgReceiver::getUserId, Function.identity()));
//            result.stream().filter(item -> receiverMap.containsKey(item.getUserId())).forEach(item -> {
//                SysMsgReceiver cur = receiverMap.get(item.getUserId());
//                this.receiverService.updateReceiverStatus(cur, item.getResult());
////			this.recordService.insert(new SysMsgRecord(cur, item));
//            });
//        }
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
//    public int insert(SysMsg entity) {
//        entity.preInsert();
//        if (CollectionUtils.isNotEmpty(entity.getAttaches())) {
//            entity.getAttaches().stream().forEach(attach -> attach.setMsgId(entity.getId()));
//            this.attachService.insertBatch(entity.getAttaches());
//        }
//        List<SysMsgTemplateContent> contents = null;
//        if (StringUtils.isNotBlank(entity.getTemplateId())) {
//            contents = this.contentService.selectList(new QueryWrapper<SysMsgTemplateContent>().eq("template_id", entity.getTemplateId()));
//            String subject = StringUtils.isNotBlank(entity.getSubject()) ? entity.getSubject() : "";
//            String content = StringUtils.isNotBlank(entity.getContent()) ? entity.getContent() : "";
//            for (Map.Entry<String, Object> entry : entity.getParams().entrySet()) {
//                subject = subject.replace("${" + entry.getKey() + "}", entry.getValue().toString());
//                content = content.replace("${" + entry.getKey() + "}", entry.getValue().toString());
//                contents.stream().forEach(item -> item.setContent(item.getContent().replace("${" + entry.getKey() + "}", entry.getValue().toString())));
//            }
//            entity.setSubject(subject);
//            entity.setContent(content);
//        }
//        Map<String, String> msgMap = CollectionUtils.isNotEmpty(contents) ? contents.stream().collect(Collectors.toMap(SysMsgTemplateContent::getChannel, SysMsgTemplateContent::getContent)) : new HashMap<>();
//        int flag = this.baseMapper.insert(entity);
//        if (CollectionUtils.isNotEmpty(entity.getUsers())) {
//            for (String channel : entity.getChannels()) {
//                entity.getUsers().stream().forEach(receiver -> {
//                    if (!MsgChannel.CHANNEL_OA.getCode().equalsIgnoreCase(channel)) {
//                        SysMsgReceiver cur = new SysMsgReceiver(entity.getId(), channel, receiver);
//                        cur.setSubject(entity.getSubject());
//                        String content = msgMap.getOrDefault(channel, entity.getContent());
//                        cur.setContent(content);
//                        this.receiverService.insert(cur);
//                    } else {
//                        if (receiver.getGipUser()) {
//                            SysMsgReceiver cur = new SysMsgReceiver(entity.getId(), channel, receiver);
//                            cur.setSubject(entity.getSubject());
//                            String content = msgMap.getOrDefault(channel, entity.getContent());
//                            cur.setContent(content);
//                            this.receiverService.insert(cur);
//                        }
//                    }
//                });
//                String routing = MsgChannel.getRouting(channel);
//                if (StringUtils.isNotBlank(routing)) {
//                    this.template.convertAndSend(MsgQueueContant.EXCHANGE_KEY, routing, entity.getId());
//                }
//            }
//        }
//        return flag;
//    }
//
//    @Override
//    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
//    public int update(SysMsg entity) {
//        entity.preUpdate();
//        return this.baseMapper.update(entity);
//    }
}
